{% extends "auth/base.html" %}

{% block title %}权限管理 - FlaskWeb{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>
        <i class="fas fa-key me-2"></i>权限管理
    </h2>
    <div>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPermissionModal">
            <i class="fas fa-plus me-1"></i>添加权限
        </button>
    </div>
</div>

<div class="card shadow">
    <div class="card-header">
        <h5 class="mb-0">权限列表</h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>权限名称</th>
                        <th>权限代码</th>
                        <th>描述</th>
                        <th>角色数量</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for permission in permissions %}
                    <tr>
                        <td>{{ permission.id }}</td>
                        <td>
                            <span class="badge bg-info">{{ permission.name }}</span>
                        </td>
                        <td><code>{{ permission.code }}</code></td>
                        <td>{{ permission.description or '-' }}</td>
                        <td>{{ permission.roles|length }}</td>
                        <td>{{ permission.created_at.strftime('%Y-%m-%d') if permission.created_at else '-' }}</td>
                        <td>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-sm btn-outline-primary edit-permission" data-permission-id="{{ permission.id }}">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-info view-roles" data-permission-id="{{ permission.id }}">
                                    <i class="fas fa-users"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 添加权限模态框 -->
<div class="modal fade" id="addPermissionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加权限</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addPermissionForm">
                    <div class="mb-3">
                        <label for="permissionName" class="form-label">权限名称</label>
                        <input type="text" class="form-control" id="permissionName" required>
                    </div>
                    <div class="mb-3">
                        <label for="permissionCode" class="form-label">权限代码</label>
                        <input type="text" class="form-control" id="permissionCode" required>
                        <div class="form-text">权限代码应该是唯一的，例如：user:read, post:write</div>
                    </div>
                    <div class="mb-3">
                        <label for="permissionDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="permissionDescription" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="savePermissionBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 查看角色模态框 -->
<div class="modal fade" id="viewRolesModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">拥有此权限的角色</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="rolesList">
                    <!-- 角色列表将通过AJAX加载 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 添加权限
    document.getElementById('savePermissionBtn').addEventListener('click', function() {
        // 构建数据对象
        const permissionData = {
            name: document.getElementById('permissionName').value,
            code: document.getElementById('permissionCode').value,
            description: document.getElementById('permissionDescription').value
        };
        
        // 发送AJAX请求
        fetch('{{ url_for("api.create_permission") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(permissionData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('addPermissionModal'));
                modal.hide();
                
                // 显示成功消息
                alert('权限添加成功');
                
                // 刷新页面
                window.location.reload();
            } else {
                alert('添加权限失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('添加权限失败');
        });
    });
    
    // 查看角色
    document.querySelectorAll('.view-roles').forEach(button => {
        button.addEventListener('click', function() {
            const permissionId = this.getAttribute('data-permission-id');
            
            // 获取拥有此权限的角色
            fetch(`{{ url_for("api.get_permission_roles") }}?permission_id=${permissionId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 构建角色列表HTML
                    let rolesHtml = '';
                    if (data.roles.length === 0) {
                        rolesHtml = '<p class="text-muted">没有角色拥有此权限</p>';
                    } else {
                        rolesHtml = '<div class="list-group">';
                        data.roles.forEach(role => {
                            rolesHtml += `
                                <div class="list-group-item">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1">${role.name}</h6>
                                        <small>用户数: ${role.user_count || 0}</small>
                                    </div>
                                    <p class="mb-1">${role.description || '无描述'}</p>
                                </div>
                            `;
                        });
                        rolesHtml += '</div>';
                    }
                    
                    // 设置角色列表
                    document.getElementById('rolesList').innerHTML = rolesHtml;
                    
                    // 显示模态框
                    const modal = new bootstrap.Modal(document.getElementById('viewRolesModal'));
                    modal.show();
                } else {
                    alert('获取角色列表失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取角色列表失败');
            });
        });
    });
</script>
{% endblock %}